package lily.phs.urh;

import lily.phs.database.Constants;
import lily.phs.object.HereTipa;
import lily.ui.bookshelf.ShelfView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ShelfActivity extends Activity implements Constants{
	
	private static final String[] panelItems = new String[]{"新建","查询","刷新"};
	private static final int[] panelImages = new int[]{R.drawable.add_files,R.drawable.search_file,R.drawable.fresh};
	private ShelfView shelf;
	private ProgressDialog mpDialog;
	private TextView tvTitle;
	private Button btnBack,btnSum,rightBtn,rightBtn0;
	private ImageButton ibtnLast, ibtnNext;
	private Button btnPage;
	private ImageButton ibtnAdd,ibtnSearch,ibtnRefresh;
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what){
			case 1:{
				shelf.refresh();
				btnSum.setText("总数："+shelf.getFileSum());
				displayPage();
				
				mpDialog.cancel();
				break;
			}
			case 2:{//新建档案页面跳转
				Intent intent = new Intent();
				intent.setClass(ShelfActivity.this, BuildProfile.class);
				startActivityForResult(intent,1);
				overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
    			mpDialog.cancel();
				break;
			}
			case 3:{//查看档案跳转
    			Intent editprofile = new Intent();
    			Bundle bd = new Bundle();
    			bd.putInt("Profile_id", msg.arg1);
    			bd.putInt("father", MODULE_FATHER);
    			bd.putInt("call", MODULE_LIST);
    			editprofile.putExtras(bd);
    			editprofile.setClass(ShelfActivity.this, PeopleScrollActivity.class);
    			startActivityForResult(editprofile,1);
    			
    			overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
    			mpDialog.cancel();
    			break;
    		}
			}
		}
		
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.shelf);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.i_title_2);
		
		tvTitle = (TextView)this.findViewById(R.id.title);
		String village = getSharedPreferences(USERINFO,Context.MODE_PRIVATE).getString("def_village", "");
		tvTitle.setText(village+"健康档案管理");
		btnBack = (Button) this.findViewById(R.id.title_left_btn);
        rightBtn = (Button) this.findViewById(R.id.title_right_btn);
        rightBtn0 = (Button) this.findViewById(R.id.title_right_btn0);
        btnSum = (Button) this.findViewById(R.id.title_right_btn2);
        btnBack.setText("后退");
        rightBtn.setVisibility(View.GONE);
        rightBtn0.setVisibility(View.GONE);
        btnSum.setBackgroundResource(R.drawable.transparent);
        
        ibtnLast = (ImageButton)this.findViewById(R.id.last);
        ibtnNext = (ImageButton)this.findViewById(R.id.next);
        btnPage = (Button)this.findViewById(R.id.page);
        ibtnAdd = (ImageButton)this.findViewById(R.id.build_file);
        ibtnSearch = (ImageButton)this.findViewById(R.id.search_file);
        ibtnRefresh = (ImageButton)this.findViewById(R.id.refresh_file);

        mpDialog = new ProgressDialog(this);  
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
		mpDialog.setMessage("正在加载...");  
		mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
		mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消 
		mpDialog.show();
		
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				
				final String[] PROJECTION = new String[]{
					HETI_HERE_ID/*显示的档案ID*/, 
					HETI_PROFILEID/*内部适用于的档案ID，用于数据库各个表之间的链接*/,
					/*提交到服务器上之后，两者一致
					 * heti_here_id(18)=area_code(12)+heti_profileid(6)
					 * */
					HETI_NAME};
				shelf.loadData(CONTENT_URI_TB1, PROJECTION, null);
				
				Message message = handler.obtainMessage();
				message.what=1;
				handler.sendMessage(message);
			}
		}.start();
        
        shelf = (ShelfView)this.findViewById(R.id.shelf);
        
        //新建
        ibtnAdd.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mpDialog.setMessage("正在准备档案，请稍候...");
				mpDialog.show();
				Message msg = handler.obtainMessage();
				msg.what=2;
				handler.sendMessageDelayed(msg, 200);
				
			}
		});
        
        //查询
        ibtnSearch.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        
        //刷新
        ibtnRefresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        

		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				shelf.close();
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
		});
		
		/**
		 * 加载上一页档案
		 */
		ibtnLast.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				shelf.loadLastPage();
				shelf.refresh();
				displayPage();
			}
		});
		
		/**
		 * 加载下一页档案
		 */
		ibtnNext.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				shelf.loadNextPage();
				shelf.refresh();
				displayPage();
			}
		});
		
		btnPage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				final View view = inflater.inflate(R.layout.text_entry, null);
				final EditText etPage = (EditText)view.findViewById(R.id.enter_page);
				
				new AlertDialog.Builder(ShelfActivity.this)
				.setTitle("查询")
				.setView(view)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						try{
							int page = Integer.parseInt(etPage.getText().toString());
							if(page<1||page>shelf.getPages()){
								Toast.makeText(ShelfActivity.this, "输入的页码超出范围", Toast.LENGTH_LONG).show();
							}
							else{
								shelf.setIndex(page);
								shelf.loadPage();
								shelf.refresh();
								displayPage();
							}
						}
						catch(Exception e){
							e.printStackTrace();
							Toast.makeText(ShelfActivity.this, "输入的页码错误", Toast.LENGTH_LONG).show();
						}
						
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				})
				.create().show();
				
			}
		});
		
		shelf.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				int profileid = view.getId();//档案编号
				Log.i("shelf", "file clicked="+profileid);
				if(profileid!=-1){
					mpDialog.setMessage("正在加载档案，请稍候...");  
					mpDialog.show();
					Message msg = handler.obtainMessage();
					msg.what=3;
					msg.arg1 = profileid;
					handler.sendMessageDelayed(msg, 200);
				}
			}
			
		});
    }
    
    /**
     * 更新页码的显示
     */
    protected void displayPage() {
		// TODO Auto-generated method stub
    	btnPage.setText(shelf.getIndex()+"/"+shelf.getPages()+"页");
		if(shelf.getIndex()==1){
			ibtnLast.setEnabled(false);
		}
		else{
			ibtnLast.setEnabled(true);
		}
		if(shelf.getIndex()==shelf.getPages()){
			ibtnNext.setEnabled(false);
		}
		else{
			ibtnNext.setEnabled(true);
		}
	}



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==RESULT_OK){
			Log.i("build profile", "ok");
			Bundle bundle = data.getExtras();
			final String name = bundle.getString("build_name");
			final int id = bundle.getInt("build_id");
			mpDialog.setMessage("正在加载......");
			mpDialog.show();
			new Thread(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					shelf.addFileToLast(name, id);
					Message message = handler.obtainMessage();
					message.what=1;
					handler.sendMessage(message);
				}
				
			}.start();
		}
		else if(resultCode==RESULT_DELETE){//删除档案，重新刷新界面
			Bundle bundle = data.getExtras();
			final String name = bundle.getString("delete_name");
			final int id = bundle.getInt("delete_id");
			mpDialog.setMessage("正在加载......");
			mpDialog.show();
			new Thread(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					shelf.deleteFile(name, id);
					Message message = handler.obtainMessage();
					message.what=1;
					handler.sendMessage(message);
				}
				
			}.start();
			
		}
		
		
	}



//	/**
//     * 控制面板adapter
//     */
//    class PanelAdapter extends BaseAdapter{
//
//    	private int sum;
//    	private String[] item;
//    	private int[] image;
//    	private LayoutInflater inflater;
//    	
//    	PanelAdapter(Context context,String[] items,int[] images){
//    		sum = items.length;
//    		this.item = items;
//    		this.image = images;
//    		inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//    	}
//    	
//		@Override
//		public int getCount() {
//			// TODO Auto-generated method stub
//			return sum;
//		}
//
//		@Override
//		public Object getItem(int position) {
//			// TODO Auto-generated method stub
//			return null;
//		}
//
//		@Override
//		public long getItemId(int position) {
//			// TODO Auto-generated method stub
//			return position;
//		}
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			// TODO Auto-generated method stub
//			ViewHolder holder;
//			if(convertView==null){
//				convertView = inflater.inflate(R.layout.panel_griditem_view, null);
//				holder = new ViewHolder();
//				holder.iv = (ImageView)convertView.findViewById(R.id.panel_item_iamge);
//				holder.tv = (TextView)convertView.findViewById(R.id.panel_item);
//				convertView.setTag(holder);
//			}
//			else{
//				holder = (ViewHolder) convertView.getTag();
//			}
//			holder.iv.setImageResource(image[position]);
//			holder.tv.setText(item[position]);
//			
//			return convertView;
//		}
//		
//		class ViewHolder{
//			ImageView iv;
//			TextView tv;
//		}
//    	
//    }
}